import threading
import csv
from carcontroller import CarController


class CANsendThread(threading.Thread):
    def __init__(self, carcontroller):
        super(CANsendThread, self).__init__()
        self.carController = carcontroller
        self.running = True

    def run(self) -> None:  # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        print('Strating ' + self.name)
        self.carController.keyboard_ctl()
        print('Exiting' + self.name)


class CANreceThread(threading.Thread):
    def __init__(self, carcontroller):
        super(CANreceThread, self).__init__()
        self.carController = carcontroller
        self.running = True

    def run(self) -> None:  # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        print('Strating ' + self.name)
        # with open('receive.txt','w',encoding='utf-8') as file:
        #     while True:
        #         file.write(str(self.carController.recv()))
        #         file.flush()

        with open('./data/receive.csv', 'a', newline='', encoding='utf-8') as csvfile:
            while self.running:
                writer = csv.writer(csvfile, delimiter=' ')
                writer.writerow(self.carController.recv())
        print('Exiting' + self.name)




if __name__ == '__main__':
    print('run')
    carcontroller = CarController()
    CANsendThread(carcontroller).start()
    CANreceThread(carcontroller).start()